package com.me.service;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.object.SqlQuery;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.me.entity.RecentChat;

@Service
public class RecentChatService {

	@Autowired
	HibernateTemplate hibernateTemplate;

	@Transactional
	public void save(RecentChat rc) throws Exception {

		hibernateTemplate.save(rc);

	}

	public List getRecent(int uid,int fid,String type){
		List list=hibernateTemplate.find("from RecentChat where type='"+type+"' and (uid="+fid+" and fid="+uid+" or uid="+uid+" and fid="+fid+")");
		return list;
	}
	
	
	@Transactional
	public List getRecentListByUid(String uid) {

		String sql = "select groups.name as name,groups.id as tip,'group' as type from groups where groups.id in				"
				+ "(																							"
				+ "	select fid from recent_chat where uid=" + uid + " and type='group' 								"
				+ ")																							"
				+ "union all																					"
				+ "select userinfo.username as name,userinfo.account as tip,'user' as type from userinfo where userinfo.id in"
				+ "(																							"
				+ "	select fid from recent_chat where uid=" + uid
				+ " and type='user'									"
				+ ")																							";
		List list=null;
		
		try{
		Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
//		Transaction tr=session.beginTransaction();
		Query q = session.createSQLQuery(sql);
//		tr.commit();
		 list= q.list();
		}catch(Exception e){
			e.printStackTrace();
		}
		return list;
	}
	
	
	@Transactional
	public void delete(RecentChat rc){
		hibernateTemplate.delete(rc);
	}

}
